// manager/pages/addmerchantmember/index.js
import { request } from '../../../utils/request';
import WxValidate from '../../../common/WxValidate';
import validateIdent from '../../../common/validateIdent';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        contact: "",
        // 性别字典
        sexList: [],
        // 职位字典
        posList: [],
        // 业务需求字典
        busiList: [],
        // 成员标签字典
        memberTag: [],
        form: {
            // 商户id
            merchantId: "",
            // 1-个人，2-商户，3-企业，4-新型农业主体
            merchantType: 2,
            id: "",
            name: "",
            phone: "",
            sex: "",
            idCard: "",
            duties: "",
            businessDemand: "",
            memberLabel: "",
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.memberId){
            this.setData({
                ['form.id']: options.memberId,
            })
            wx.setNavigationBarTitle({
                title: "编辑成员"
            })
            this.getMerchantPartInfo();
        }
        this.setData({
            ['form.merchantId']: options.merchantId,
            contact: options.contact || ""
        })
        this.getDictionaryInfo();
        this.initValidate();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 获取性别、职位、业务需求字典
     */
    getDictionaryInfo() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
                dictType: "cif_sex"
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    sexList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "ecard_merchant_position"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    posList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "ecard_personal_business_tag"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    busiList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "ecard_personal_tag"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    memberTag: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },

    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        let { form } = this.data;
        form[key] = value;
        this.setData({
            form
        })
    },

    /**
     * 成员标签
     */
    beTag(e) {
        let { item } =  e.currentTarget.dataset;
        let arr = this.data.form.memberLabel?this.data.form.memberLabel.split(","):[];
        let index = arr.indexOf(item.dictValue);
        console.log(arr,arr.indexOf(item.dictValue))
        if(index == -1){
            arr.push(item.dictValue);
        }else{
            arr.splice(index,1);
        }
        this.setData({
            'form.memberLabel': arr.join(",")
        })
    },

    // 成员信息
    getMerchantPartInfo(){
        request({
            url: "/merchantMarketing/getMerchantPartInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.id
            }
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                for(let key in form){
                    form[key] = res.data[key];
                }
                this.setData({
                    form
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 已开通业务、营销重点选择
     */
    onCheckboxChange(e) {
        console.log(e)
        let { key, item } = e.currentTarget.dataset;
        let arr = this.data.form[key]?this.data.form[key].split(","):[];
        let index = arr.indexOf(item.dictValue);
        if(index != -1){
            arr.splice(index,1);
        }else{
            arr.push(item.dictValue);
        }
        this.setData({
            ['form.'+key]: arr.join(",")
        });
    },

    // 保存
    save(e) {
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        if(this.data.form.idCard){
            if(!validateIdent.IdentityCode_isCardNo(this.data.form.idCard)){
                this.showModal({
                    msg: "请输入18位证件号"
                })
                return false
            }
            if(!validateIdent.IdentityCode_checkProvince(this.data.form.idCard)){
                this.showModal({
                    msg: "证件号省份不正确"
                })
                return false
            }
            if(!validateIdent.IdentityCode_checkBirthday(this.data.form.idCard)){
                this.showModal({
                    msg: "证件号出生日期不正确"
                })
                return false
            }
            if(!validateIdent.IdentityCode_checkParity(this.data.form.idCard)){
                this.showModal({
                    msg: "证件号检验位不正确"
                })
                return false
            }
        }
        request({
            url: `/merchantMarketing/addMerchantPartInfo`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: this.data.form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                setTimeout(()=>{
                    if(this.data.contact){
                        wx.redirectTo({
                            url: `/manager/pages/gridvisit/index?merchantId=${this.data.form.merchantId}`,
                        })
                    }else{
                        wx.navigateBack()
                    }
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            name: {
                required: true
            },
            duties: {
                required: true
            },
            sex: {
                required: true
            },
            phone: {
                required: true,
                tel: true
            },
            // idCard: {
            //     cardNo: true,
            //     checkProvince: true,
            //     checkBirthday: true,
            //     checkParity: true,
            // },
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            name: {
                required: '请输入姓名'
            },
            duties: {
                required: '请选择职位'
            },
            sex: {
                required: '请选择性别'
            },
            phone: {
                required: '请输入电话',
                tel: '请输入正确的电话'
            },
            // idCard: {
                
            // },
            
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)        
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})